// ==UserScript==
// @name         批量创建主题
// @namespace    https://yk12510.gitee.io/static-resources/
// @version      1.0.2
// @description  try to take over the world!
// @author       You
// @match        http://www.ahedu.cn/SNS/index.php?*
// @grant        none
// @updateURL    https://yk12510.gitee.io/static-resources/002-script/aheduTheme.js
// ==/UserScript==

(function () {
  // 创建主题
  patchCreateTheme()

  function patchCreateTheme () {
    // 添加创建主题按钮
    const style = {
        '.createTheme': {
          position: 'fixed', left: '50%', top: '50%', padding: '20px',
          display: 'none', width: '460px', transform: 'translate(-50%, -50%)',
          background: '#0089AA', color: '#fff', overflow: 'auto',
          'font-size': '16px', 'border-radius': '18px'
        },
        '.createTheme .label': { 'margin-bottom': '10px', 'text-align': 'center' },
        '.createTheme p': { 'margin-bottom': '5px' },
        '.createTheme input': { padding: '3px 6px' },
        '.createTheme button': { margin: '0 5px', padding: '6px', cursor: 'pointer' },
        '.createTheme .result': { 'text-align': 'center', 'font-size': '12px' }
      },
      openCreateThemeBtn = $('<a class="fr" href="javascript:void(0)">创建主题</a>'),
      createThemeEl = $(
        '<div class="createTheme" style="max-height:' + (window.innerHeight - 40) + 'px">' +
        ' <div class="label">主题名称：<input class="theme"></div>' +
        ' <div class="label">开始序号：<input class="start" value="1"></div>' +
        ' <div class="label">创建个数：<input class="count" value="25"></div>' +
        ' <div class="label"><button class="confirm">确认创建</button><button class="cancel">取消创建</button></div>' +
        ' <div class="result"></div>' +
        '</div>'
      ).appendTo(document.body),
      resultEl = createThemeEl.find('.result'),
      timers = [] // 定时器

    // 写入样式
    let styleStr = '', styles = ''
    Object.keys(style).forEach(selector => {
      styles = ''
      Object.keys(style[selector]).forEach((styleName, index) => {
        styles += `${ styleName }:${ style[selector][styleName] };`
      })
      styleStr += `${ selector }{${ styles }}`
    })
    $(document.body).append(`<style>${ styleStr }</style>`)

    // 打开创建主题
    $('#right_header').prepend(openCreateThemeBtn)
    openCreateThemeBtn.click(() => {
      createThemeEl.toggle()
    })

    // 创建主题
    createThemeEl.find('.confirm').click(() => {
      var themeName = createThemeEl.find('.theme').val(),
        start = createThemeEl.find('.start').val(),
        count = createThemeEl.find('.count').val()
      if (themeName && start && count) {
        createTheme(themeName, start, count)
      } else {
        alert('请输入' + [themeName ? '' : '主题名称', start ? '' : '开始序号', count ? '' : '创建个数',].join('、'))
      }
    })

    // 取消创建
    createThemeEl.find('.cancel').click(function () {
      createThemeEl.hide()
      timers.forEach(function (timer) {
        clearTimeout(timer)
      })
    })

    // 创建主题
    function createTheme (themeName, start, count) {
      // 创建方法
      function createThemeFunction (tName) {
        $.post('index.php?app=research&mod=Index&act=saveInfo', {
          accessType: 0, attachids: '', res_des: '',
          tag_ids: '', to_space: 1, userids: '|',
          res_name: tName
        }, res => {
          res = JSON.parse(String(res || '{}'))
          res.status == 1
            ? resultEl.append(`<p>${ resultEl.find('p').length } ${ tName } 创建成功 ${ res.credit_info }</p>`)
            : resultEl.append(`<p>${ resultEl.find('p').length } ${ tName } ${ res.credit_info }</p>`)
        })
      }

      // 签到
      $.post(U('widget/CheckIn/check_in'), {}, () => {
        resultEl.append('<p>签到成功！</p>')
      })

      start = start || 1
      count = count || 25
      for (let i = 0; i < count; i++) {
        // 500ms发送一个请求
        timers[i] = setTimeout(() => {
          const num = i + Number(start)
          let newThemeName = themeName + (num === 1 ? '' : num)
          $.post('index.php?app=research&mod=Index&act=IsExistsByTitle', { title: newThemeName },
            status => {
              status == 1
                ? resultEl.append(`<p>${ resultEl.find('p').length } ${ newThemeName } <span style="color: red">您已发布相同主题,请勿重复发布</span></p>'`)
                : status == 0 ? createThemeFunction(newThemeName) : alert('网络错误')
            }
          )
        }, 500 * i)
      }
    }
  }

  // 删除动态
  patchDeleteWeibo()

  function patchDeleteWeibo () {
    const deleteWeiboBtn = $('<a class="fr" href="javascript:void(0)">删除动态</a>')
    if (/ahedu\.cn\/SNS\/index\.php\?.*feed_type=my.*/i.test(location.href)) {
      $('#right_header').prepend(deleteWeiboBtn)
      deleteWeiboBtn.click(() => {
        if (deleteWeiboBtn.text() === '停止删除') {
          clearInterval(timer)
          page = 1
          deleteWeiboBtn.text('删除动态')
        } else {
          init()
        }
      })
    }

    // 删除动态
    function deleteWeibo (id) {
      $.post(U('public/Feed/removeFeed'), { feed_id: id }, function (msg) {
        console.log('删除')
        if (msg.status == 1) {
          if ($('#feed' + id).length > 0) {
            $('#feed' + id).fadeOut()
          }
        } else {
          ui.error(L('PUBLIC_DELETE_ERROR'))
        }
        weiboCount--
        if (weiboCount < 1) {
          init()
        }
      }, 'json')
    }

    // 加载页面
    function loadPage (page) {
      core.weibo.loadMoreByPage(`/SNS/index.php?app=widget&mod=FeedList&act=loadMore&loadId=38806912&type=following&uid=2083239&feed_type=my&feed_key=&fgid=&topic_id=&load_count=4&p=${ page }`)
    }

    // 查询Id
    function queryIds () {
      const ids = [], allIds = []
      $('#feed-lists').find('.feed_list').each((index, item) => {
        const id = $(item).attr('id').split('feed')[1],
          text = ($(item).find('a:contains(《)').text().match(/《(.+)》/) || [null, ''])[1]
        console.log(text)
        allIds.push(id);
        (/\d+$/).test(text) && ids.push(id)
      })
      return [ids, allIds]
    }

    let weiboCount = 0, page = 1, timer = null

    function init () {
      deleteWeiboBtn.text('停止删除')
      console.log('查询第' + page + '页')
      loadPage(page)
      let count = 0
      timer = setInterval(() => {
        count++
        const idsObj = queryIds(), ids = idsObj[0], allIds = idsObj[1]
        if (allIds.length || count > 2 * 60 * 1000 / 200) { // 2分钟找不到就停止
          clearInterval(timer)

          if (ids.length) {
            ids.forEach(id => {
              weiboCount++
              deleteWeibo(id)
            })
          } else { // 没有可以删除的，加载下一页
            page++
            init()
          }
        }
      }, 200)
    }
  }

  // 删除主题
  patchDeleteTopic()

  function patchDeleteTopic () {
    const deleteTopicBtn = $('<a class="fr" href="javascript:void(0)">删除主题</a>')
    if (/ahedu\.cn\/SNS\/index\.php\?app=research&mod=Index&act=index/i.test(location.href)) {
      $('#right_header').prepend(deleteTopicBtn)
      deleteTopicBtn.click(() => {
        if (deleteTopicBtn.text() === '停止删除') {
          clearTimeout(timer)
          page = 1
          deleteTopicBtn.text('删除主题')
        } else {
          init()
        }
      })
    }

    // 查询可删除的主题Id
    function queryIds () {
      const ids = []
      $('.topic_name a').each((index, item) => {
        let href = $(item).attr('href'),
          name = $(item).text()
        if (/\d+/.test(name)) {
          let id = (href.match(/id=\d+/) || [])[0]
          id && ids.push(id.split('=')[1])
          $(item).closest('dd').attr('rid', id.split('=')[1])
        }
      })
      return ids
    }

    // 删除主题
    function deleteTheme (rid) {
      $.post(U('research/Index/deleteResearch'), { rid: rid }, () => {
        deleteCount--
        $('dd[rid="' + rid + '"]').fadeOut()
        if (deleteCount < 1) {
          create.loadData(page)
          setTimeout(init, 500)
        }
      })
    }

    // 初始化
    let timer = null, queryCount = 0, deleteCount = 0, page = 1

    function init () {
      deleteTopicBtn.text('停止删除')
      // 检测主题存在
      let topicList = $('.topic_name a')
      if (topicList.length) {
        queryCount = 0
        deleteCount = 0
        const ids = queryIds()
        if (ids.length) {
          ids.forEach(id => {
            deleteCount++
            deleteTheme(id)
          })
        } else if ($('.present2').length && $('.present2').text() < (page + 2)) {
          create.loadData(++page)
          init()
        }
      } else {
        if (queryCount < (5 * 60 * 2)) setTimeout(init, 500) // 500毫秒后再查一次
      }
    }
  }
})()
